#!/bin/bash
#description  configure install mysql server
#MySQL define path variable
M_SOFT="mysql-5.5.59.tar.gz"
M_SOFT_DIR="mysql-5.5.59"
M_URL="https://cdn.mysql.com//Downloads/MySQL-5.5/"
M_PREFIX="/usr/local/mysql"
DATADIR="/data/mysql"
USER="mysql"
SOFTDIR="/usr/local/src"
#Install mysql prerequisites
  yum -y install ncurses-devel cmake make perl gcc autoconf automake zlib zlib-devel libxml libxml-devel bison-devel
#create mysql user
if ! id $USER &>/dev/null ;then
       groupadd -g 3306 mysql           
       useradd -u 3306 -g mysql -s /sbin/nologin -r mysql
fi
#create mysql directory
if [ ! -d $DATADIR ];then
      mkdir -p $DATADIR
fi
#download mysql software
    cd $SOFTDIR && wget ${M_URL}/${M_SOFT} && tar xf ${M_SOFT} && cd ${M_SOFT_DIR} && \
   cmake -DCMAKE_INSTALL_PREFIX=${M_PREFIX} -DMYSQL_DATADIR=${DATADIR} -DSYSCONFDIR=/etc/mysql -DWITH_MYISAM_STORAGE_ENGINE=1 -DWITH_INNOBASE_STORAGE_ENGINE=1 \
        -DWITH_MEMORY_STORAGE_ENGINE=1 -DWITH_READLINE=1 -DMYSQL_UNIX_ADDR=/var/lib/mysql/mysql.sock  -DMYSQL_USER=mysql -DMYSQL_TCP_PORT=3306 -DENABLED_LOCAL_INFILE=1 \
        -DWITH_PARTITION_STORAGE_ENGINE=1 -DEXTRA_CHARSETS=all -DDEFAULT_CHARSET=utf8mb4 -DDEFAULT_COLLATION=utf8mb4_general_ci
       if [ $? -eq 0 ];then
                make && make install
       fi
       #configure mysql server
       chown -R $USER:$USER ${DATADIR}
       cd ${M_PREFIX} && scripts/mysql_install_db --basedir=${M_PREFIX} --datadir=${DATADIR} --user=$USER
       cp support-files/mysql.server /etc/init.d/mysqld
       chmod u+x /etc/init.d/mysqld
       chkconfig mysql on
       mv /etc/my.cnf{,.ori}
     # cp support-files/my-default.cnf /etc/my.cnf  
cat >/etc/my.cnf <<EOF
[mysqld]
port = 3306
socket = /tmp/mysql.sock
skip-external-locking
key_buffer_size = 256M
max_allowed_packet = 1M
table_open_cache = 256
sort_buffer_size = 1M
read_buffer_size = 1M
read_rnd_buffer_size = 4M
myisam_sort_buffer_size = 64M
thread_cache_size = 8
query_cache_size= 16M
datadir=/data/mysql
innodb_log_file_size = 1G
log_error = error.log
skip_name_resolve = 1
EOF
cat >> /etc/security/limits.d/80-mysql.conf <<EOF
mysql soft nofile 40960
mysql hard nofile 40960
EOF
# configure path env
echo "export PATH=${M_PREFIX}/bin:$PATH" >> /etc/profile.d/mysql.sh
source /etc/profile.d/mysql.sh
#start mysql server
service mysqld start

